package org.springleaf.core.mvc.controller;

import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springleaf.core.query.QueryObject;

/**
 * 渲染Json的Controller
 * @author leaf
 * @param <T>
 */
public abstract class JsonApiController<T> extends ApiController<T> {

	/**
	 * 跳到首页
	 * @return
	 * @throws Exception
	 */
	@RequestMapping
	public ModelAndView index() throws Exception {
		return render(getBeanName());
	}

	/**
	 * 通过ID得到对象
	 * @param id
	 */
	@RequestMapping("{id}")
	public ModelAndView get(@PathVariable("id") Long id) throws Exception {
		return renderJson(getModel(id));
	}

	/**
	 * 查询
	 * @param queryObj
	 */
	@RequestMapping("list")
	public ModelAndView list(QueryObject queryObj) throws Exception {
		return renderJson(queryModel(queryObj));
	}

	/**
	 * 保存
	 * @param obj
	 */
	@RequestMapping("save")
	public ModelAndView save(T obj) throws Exception {
		Object id = saveModel(obj);
		if (id != null) {
			return renderJson(true, "添加成功");
		}
		return renderJson(false, "添加失败");
	}

	/**
	 * 更改
	 * @param id
	 * @param obj
	 */
	@RequestMapping("update")
	public ModelAndView update(Long id, T obj) throws Exception {
		T model = updateModel(id, obj);
		if (model != null) {
			return renderJson(true, " 资料修改成功");
		}
		return renderJson(false, " 资料修改失败,不存在的数据");
	}

	/**
	 * 删除
	 * @param id
	 * @return
	 */
	@RequestMapping("delete/{id}")
	public ModelAndView delete(@PathVariable("id") Long id) throws Exception {
		deleteModel(id);
		return renderJson(true, " 删除成功");
	}
	
}
